import _ from 'lodash';
import { ipcMain, Event, webContents, BrowserWindow, screen } from 'electron';
import IElectronModule from './bg_base'

export const PRINTER_LIST = "printer-list";
export const PRINTER_LIST_RET = "printer-list-ret";
export const PRINTER_OPEN = "printer-open";
export const PRINTER_OPEN_RET = "printer-open-ret";
export const PRINTER_CLOSE = "printer-close";
export const PRINTER_CLOSE_RET = "printer-close-ret";
export const PRINTER_DO = "printer-do";
export const PRINTER_DO_RET = "printer-do-ret";

/** 打印窗口宽度 */
export const PRINTER_WIN_WIDTH = 350;

/**
 * 打印处理
 */
class PrinterHelper implements IElectronModule {

    private win?: BrowserWindow;
    private printer_win?: BrowserWindow;

    private printer_width = PRINTER_WIN_WIDTH;
    // private _database_map: Map<string, lowdb.LowdbSync<any>> = new Map<string, lowdb.LowdbSync<any>>();

    install(win: BrowserWindow): void {
        this.win = win;
        ipcMain.on(PRINTER_LIST, this.allPrinterList.bind(this));
        ipcMain.on(PRINTER_OPEN, this.openPrinterWin.bind(this));
        ipcMain.on(PRINTER_CLOSE, this.closePrinterWin.bind(this));
        ipcMain.on(PRINTER_DO, this.doPrint.bind(this));
    }

    /**
     * 获取打印机列表
     * @param event 
     */
    private allPrinterList(event: Event) {
        console.log("开始获取打印机");
        //let allWC = webContents.getAllWebContents();

        if (this.win) {
            let printerList = this.win.webContents.getPrinters();
            event.sender.send(PRINTER_LIST_RET, {
                status: "success",
                message: "",
                printerList
            });
        } else {
            event.sender.send(PRINTER_LIST_RET, {
                status: "success",
                message: "没有打印机",
                printerList: []
            });
        }
    }

    /**
     * 打开打印窗口
     * @param event 
     * @param param1 
     */
    private openPrinterWin(event: Event, {
        page = "",
        width = PRINTER_WIN_WIDTH
    }: { page?: string, width?: number } = {}) {
        this.printer_width = width;

        if (!this.printer_win && this.win) {
            // 创建打印窗口
            this.printer_win = new BrowserWindow({
                // x: parent_bounds.x - 375,
                // y: parent_bounds.y,
                // width: 375,
                // height: parent_bounds.height,
                parent: this.win,
                resizable: false,
                minimizable: false,
                movable: false,
                show: false,
                frame: false,
                transparent: true,
            })
            this.setPrinterBounds();
            this.setPrinterOpacity();
            this.printer_win.setMenu(null);
            this.printer_win.webContents.openDevTools();

            const b = () => {
                this.setPrinterBounds();
                this.setPrinterOpacity();
            };
            this.win.on("move", b);
            this.win.on("resize", b);

            this.printer_win
                .on("closed", () => {
                    if (this.win) {
                        this.win.removeListener("move", b);
                        this.win.removeListener("resize", b);
                    }
                    this.printer_win = undefined;
                })
                .on("ready-to-show", () => this.printer_win && this.printer_win.show())
                .on("focus", this.setPrinterOpacity.bind(this))
                .on("blur", this.setPrinterOpacity.bind(this));
        }

        // 加载目标页面
        if (this.printer_win) {
            if (process.env.WEBPACK_DEV_SERVER_URL) {
                this.printer_win.loadURL(process.env.WEBPACK_DEV_SERVER_URL + "print.html#/" + page)
            } else {
                this.printer_win.loadURL('app://./print.html#/' + page)
            }

        }
        event.sender.send(PRINTER_OPEN_RET, {
            status: "success",
            message: ""
        });
    }

    /** 设定恰当的打印窗口位置 */
    private setPrinterBounds() {
        if (this.win && this.printer_win) {
            const { x: parent_x, y: parent_y, width: parent_width, height: parent_height } = this.win.getBounds();
            const { width: display_width, height: display_height } = screen.getPrimaryDisplay().size;

            this.printer_win.setBounds({
                x: _.max([0, parent_x - this.printer_width + 8]) as number,
                y: _.max([0, parent_y]) as number,
                width: this.printer_width,
                height: _.min([parent_height - 8, display_height]) as number,
            })
        }
    }

    /** 配置打印窗口的透明度 */
    private setPrinterOpacity() {
        if (this.win && this.printer_win) {
            const { x: parent_x } = this.win.getBounds();
            this.printer_win.setOpacity(
                parent_x + 8 < this.printer_width && !this.printer_win.isFocused()
                    ? 0.5
                    : 1
            );
        }
    }

    /** 关闭打印窗口 */
    private closePrinterWin(event: Event) {
        if (this.printer_win) {
            this.printer_win.close();
        }
        event.sender.send(PRINTER_CLOSE_RET, {
            status: "success",
            message: ""
        });
    }

    /** 开始打印 */
    private doPrint(event: Event, { deviceName = "" }: any) {
        if (this.printer_win) {
            this.printer_win.webContents.print({
                // silent: true,
                // deviceName,
            }, res => {
                event.sender.send(PRINTER_DO_RET, {
                    status: "success",
                    message: res ? "打印成功" : "打印失败"
                });
            });
        }
        else {
            event.sender.send(PRINTER_DO_RET, {
                status: "error",
                message: "未指定打印页面"
            });
        }
    }

}

export default new PrinterHelper();